package com.liannong.controller;

import com.liannong.common.Result;
import com.liannong.service.UserCartService;
import com.liannong.vo.CartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {
    
    private static final Logger logger = LoggerFactory.getLogger(CartController.class);

    @Autowired
    private UserCartService userCartService;

    /**
     * 添加商品到购物车
     * @param userId 用户ID
     * @param productId 商品ID
     * @param quantity 数量
     * @return 添加结果
     */
    @PostMapping("/save/{userId}")
    public Result save(
            @PathVariable Integer userId,
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) Integer quantity,
            @RequestBody(required = false) Map<String, Object> requestBody) {
        
        logger.info("收到加入购物车请求 - userId: {}, URL参数 productId: {}, quantity: {}, 请求体: {}", 
                userId, productId, quantity, requestBody);
        
        // 先尝试从请求体获取参数
        if (requestBody != null) {
            // 支持多种类型参数 (Integer或String)
            if (productId == null && requestBody.containsKey("productId")) {
                Object productIdObj = requestBody.get("productId");
                if (productIdObj != null) {
                    try {
                        if (productIdObj instanceof Integer) {
                            productId = (Integer) productIdObj;
                        } else if (productIdObj instanceof String) {
                            productId = Integer.parseInt((String) productIdObj);
                        } else if (productIdObj instanceof Number) {
                            productId = ((Number) productIdObj).intValue();
                        }
                    } catch (Exception e) {
                        logger.error("解析productId参数错误: {}", e.getMessage());
                    }
                }
            }
            
            if (quantity == null && requestBody.containsKey("quantity")) {
                Object quantityObj = requestBody.get("quantity");
                if (quantityObj != null) {
                    try {
                        if (quantityObj instanceof Integer) {
                            quantity = (Integer) quantityObj;
                        } else if (quantityObj instanceof String) {
                            quantity = Integer.parseInt((String) quantityObj);
                        } else if (quantityObj instanceof Number) {
                            quantity = ((Number) quantityObj).intValue();
                        }
                    } catch (Exception e) {
                        logger.error("解析quantity参数错误: {}", e.getMessage());
                    }
                }
            }
        }
        
        logger.info("解析后参数 - productId: {}, quantity: {}", productId, quantity);
        
        // 参数验证
        if (productId == null || quantity == null) {
            logger.warn("参数为空 - productId: {}, quantity: {}", productId, quantity);
            return Result.error("400", "参数不能为空");
        }
        
        boolean success = userCartService.addToCart(userId, productId, quantity);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 更新购物车商品数量
     * @param cartId 购物车ID
     * @param quantity 数量
     * @param selected 选中状态
     * @return 更新结果
     */
    @PutMapping("/update/{cartId}")
    public Result update(
            @PathVariable Long cartId,
            @RequestParam(required = false) Integer quantity,
            @RequestParam(required = false) Boolean selected,
            @RequestBody(required = false) Map<String, Object> requestBody) {
        
        logger.info("更新购物车请求 - cartId: {}, quantity: {}, selected: {}, requestBody: {}", 
                cartId, quantity, selected, requestBody);
        
        // 先尝试从请求体获取参数
        if (requestBody != null) {
            // 处理quantity参数
            if (quantity == null && requestBody.containsKey("quantity")) {
                Object quantityObj = requestBody.get("quantity");
                if (quantityObj != null) {
                    try {
                        if (quantityObj instanceof Integer) {
                            quantity = (Integer) quantityObj;
                        } else if (quantityObj instanceof String) {
                            quantity = Integer.parseInt((String) quantityObj);
                        } else if (quantityObj instanceof Number) {
                            quantity = ((Number) quantityObj).intValue();
                        }
                    } catch (Exception e) {
                        logger.error("解析quantity参数错误: {}", e.getMessage());
                    }
                }
            }
            
            // 处理selected参数
            if (selected == null && requestBody.containsKey("selected")) {
                Object selectedObj = requestBody.get("selected");
                if (selectedObj != null) {
                    try {
                        if (selectedObj instanceof Boolean) {
                            selected = (Boolean) selectedObj;
                        } else if (selectedObj instanceof String) {
                            selected = Boolean.parseBoolean((String) selectedObj);
                        } else if (selectedObj instanceof Integer) {
                            selected = ((Integer) selectedObj) == 1;
                        } else if (selectedObj instanceof Number) {
                            selected = ((Number) selectedObj).intValue() == 1;
                        }
                    } catch (Exception e) {
                        logger.error("解析selected参数错误: {}", e.getMessage());
                    }
                }
            }
        }
        
        logger.info("解析后参数 - quantity: {}, selected: {}", quantity, selected);
        
        // 根据传入参数的不同，分别更新数量或选中状态
        if (quantity != null) {
            boolean success = userCartService.updateQuantity(cartId, quantity);
            if (success) {
                return Result.success();
            } else {
                return Result.error();
            }
        } else if (selected != null) {
            boolean success = userCartService.updateSelected(cartId, selected);
            if (success) {
                return Result.success();
            } else {
                return Result.error();
            }
        } else {
            return Result.error("400", "需要提供quantity或selected参数");
        }
    }

    /**
     * 删除购物车商品
     * @param cartId 购物车ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteById/{cartId}")
    public Result deleteById(@PathVariable Long cartId) {
        boolean success = userCartService.removeFromCart(cartId);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 获取用户购物车列表
     * @param userId 用户ID
     * @return 购物车列表
     */
    @GetMapping("/findByUserId/{userId}")
    public Result findByUserId(@PathVariable Integer userId) {
        List<CartVO> cartList = userCartService.getUserCart(userId);
        return Result.success(cartList);
    }

    /**
     * 清空用户购物车
     * @param userId 用户ID
     * @return 清空结果
     */
    @DeleteMapping("/clear/{userId}")
    public Result clear(@PathVariable Integer userId) {
        boolean success = userCartService.clearCart(userId);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }
} 